package com.laoxiang.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laoxiang.execption.LxAdminException;
import com.laoxiang.modules.system.entity.SysUserRole;
import com.laoxiang.modules.system.mapper.SysUserRoleMapper;
import com.laoxiang.modules.system.service.SysUserRoleService;
import com.laoxiang.utils.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户角色关系表(SysUserRole)表服务实现类
 *
 * @author db
 * @since 2023-07-26 19:37:16
 */
@Service
@Slf4j
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public int countUserRoleByRoleId(Long roleId) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getRoleId,roleId);
        Integer count = sysUserRoleMapper.selectCount(queryWrapper);
        return count;
    }

    @Override
    public void deleteUserRoleByUserId(Long userId) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId,userId);
        int count = sysUserRoleMapper.delete(queryWrapper);
        if(count == 0){
            log.error("删除用户角色信息失败");
            throw new LxAdminException(AppHttpCodeEnum.USER_ROLE_DELETE_ERROR.getCode(),AppHttpCodeEnum.USER_ROLE_DELETE_ERROR.getMsg());
        }

    }

    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Objects.nonNull(userId),SysUserRole::getUserId,userId);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(queryWrapper);
        List<Long> roleIds = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        return roleIds;
    }
}

